package com.yj.timecapsule.controller.common;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.yj.timecapsule.common.enums.ErrorCode;
import com.yj.timecapsule.common.error.BusinessException;
import com.yj.timecapsule.common.response.CommonResponseType;
import com.yj.timecapsule.common.utils.OssUtil;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Sean
 * @CreateTime 2024-07-30  19:43
 * @Description file upload and download
 * @Version 1.0
 */
@RestController
@RequestMapping("/file")
public class FileController {
    //在项目根目录下的temp文件夹
    private static final String TEMP_PATH = "temp/";
    @Resource
    private OssUtil ossUtil;

    @PostMapping("/upload")
    public CommonResponseType<Map<String,Object>> upload(@RequestParam("file") MultipartFile file) {
        Map<String,Object> map = new HashMap<>();
        String originalFilename = file.getOriginalFilename();

        String suffix = FileUtil.getSuffix(originalFilename);
        String idStr = IdUtil.getSnowflake().nextIdStr();
        // 如果TEMP_PATH不存在 就创建目录
        File tempDir = new File(TEMP_PATH);
        if (!tempDir.exists()){
            tempDir.mkdirs();
        }
        String fileName = idStr + "." + suffix;

        String filePath = TEMP_PATH + fileName;
        try {
            byte[] bytes = file.getBytes();
            try (FileOutputStream fos = new FileOutputStream(filePath)) {
                fos.write(bytes);
            }
            String url = ossUtil.upload(fileName, filePath);
            map.put("url", url);
            map.put("base64", Base64.encode(file.getInputStream()));
            return CommonResponseType.success(map);
        }catch (IOException ie){
            throw new BusinessException(ErrorCode.FILE_UPLOAD_ERROR);
        }

    }
}
